<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { getUserInfo, updateUserInfo } from '@/apis/user'
import { uploadAvatarFile } from '@/apis/file'
import { useAccountStore } from '@/stores/useAccountStore'
import { useRouter } from 'vue-router'
const router = useRouter()
// 表单引用
const ruleFormRef = ref<FormInstance>()
const accountStore = useAccountStore()
// 表单数据（根据UserInfoRespDto调整）
const ruleForm = reactive({
  username: '',
  sex: 1, // 1-男 2-女
  mail: '',
  signature: '',
  avatar: '',
})

// 验证规则调整
const rules = reactive<FormRules>({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 15, message: '长度在3-15个字符', trigger: 'blur' },
  ],
  mail: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' },
  ],
  signature: [
    { max: 100, message: '个性签名不能超过100个字符', trigger: 'blur' },
  ],
})

// 初始化用户数据
const initUserData = async () => {
  try {
    const res = await getUserInfo(accountStore.uid) // 需要实现获取当前用户ID的逻辑
    const data = res.data
    Object.assign(ruleForm, {
      username: data.username,
      sex: data.sex,
      mail: data.mail,
      signature: data.signature,
      avatar: data.avatar,
    })
  } catch (error) {
    ElMessage.error('用户信息加载失败')
  }
}

// 头像上传处理
const handleAvatarUpload = async (file: File) => {
  try {
    const formData = new FormData()
    formData.append('file', file)
    const res = await uploadAvatarFile(formData)
    ruleForm.avatar = res.data
  } catch (error) {
    ElMessage.error('头像上传失败')
  }
}

// 提交表单
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return

  await formEl.validate(async (valid) => {
    if (valid) {
      try {
        const res = await updateUserInfo({
          uid: accountStore.uid,
          username: ruleForm.username,
          sex: ruleForm.sex,
          mail: ruleForm.mail,
          signature: ruleForm.signature,
          avatar: ruleForm.avatar,
        })

        // 根据实际接口返回结构判断
        if (res.code === '200') {
          ElMessage.success('资料更新成功')
          router.push('/admin')
        } else {
          // 处理业务逻辑错误
          ElMessage.error(res.message || '更新失败，请稍后重试')
        }
      } catch (error: any) {
        // 处理网络错误和HTTP错误
        const errorMessage =
          error.response?.data?.message ||
          error.message ||
          '请求失败，请检查网络'
        ElMessage.error(errorMessage)
      }
    }
  })
}

// 重置表单
const resetForm = () => {
  initUserData()
}

onMounted(() => {
  initUserData()
})
</script>

<template>
  <div>
    <div>
      <el-text class="mainTitle">管理资料与密码</el-text>
    </div>
    <div style="display: flex">
      <el-card shadow="hover" class="box-card">
        <div class="profile">
          <el-form
            ref="ruleFormRef"
            :model="ruleForm"
            :rules="rules"
            label-width="90px"
          >
            <el-form-item label="用户头像">
              <el-avatar :src="ruleForm.avatar" style="margin-right: 10px" />
              <el-upload
                action=""
                :show-file-list="false"
                :before-upload="handleAvatarUpload"
              >
                <el-button type="primary">更换头像</el-button>
              </el-upload>
            </el-form-item>

            <el-form-item label="用户名" prop="username">
              <el-input v-model="ruleForm.username" class="input" />
            </el-form-item>

            <el-form-item label="性别" prop="sex">
              <el-radio-group v-model.number="ruleForm.sex">
                <el-radio :label="1">男</el-radio>
                <el-radio :label="2">女</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="邮箱" prop="mail">
              <el-input v-model="ruleForm.mail" class="input-mini" />
            </el-form-item>

            <el-form-item label="个性签名" prop="signature">
              <el-input
                v-model="ruleForm.signature"
                type="textarea"
                :rows="3"
                placeholder="请输入个性签名"
              />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="submitForm(ruleFormRef)">
                保存
              </el-button>
              <el-button @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-card>
      <UserPassword />
    </div>
  </div>
</template>

<style scoped>
.box-card {
  margin-top: 21px;
  margin-left: 20px;
  border-radius: 7px;
  width: 700px;
  padding-right: 30px;
}

.card {
  margin-top: 21px;
  margin-left: 20px;
  border-radius: 5px;
  width: 300px;
  height: 300px;
}

.input {
  width: 500px;
  height: 40px;
}

.input-mini {
  width: 250px;
  height: 40px;
}

.mainTitle {
  margin-left: 30px;
  font-size: 18px;
  color: #000;
  font-weight: bolder;
}

.profile {
  margin-left: 30px;
  margin-top: 20px;
}

.box-card {
  margin-top: 21px;
  margin-left: 20px;
  border-radius: 7px;
  width: 700px;
  padding-right: 30px;
}

.input {
  width: 500px;
  height: 40px;
}

.input-mini {
  width: 250px;
  height: 40px;
}

.mainTitle {
  margin-left: 30px;
  font-size: 18px;
  color: #000;
  font-weight: bolder;
}

.profile {
  margin-left: 30px;
  margin-top: 20px;
}
</style>
